import cn from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import Button from '@kuiper-components/button';
import Dialog from '@kuiper-components/dialog';
import Tooltip from '@kuiper-components/tooltip';
import Helper from '../../Helper';
import { Link } from 'react-router-dom';
import {
	NODE_ID_LABEL_MAP,
	NODE_ID_LABEL_MAP2,
	PING_FREQUENCY_NUMBERS,
	INFORM_OPTIONS,
	WEAKNESS_FREQUENCY_UNIT_MAP,
} from '../../../../common/constants';
import Label from '../../Label';
import CollectFrequency from '../../CollectFrequency';
import s from './style.module.css';
import { useQuery, gql } from '@apollo/client';
import { EyeOutlined } from '@ant-design/icons';

const ALERT_GROUP_QUERY = gql`
	{
		AlertGroupMany {
			isDefault
			receiverIds
			name
			_id
		}
	}
`;
const httpSubmitInnerBuilder = data => {
	let texts;
	if (!data) {
		texts = [
			'user-agent:Mozilla/5.0(compatible; YunaqMonitor;+http://www.yunaq.com/help/56c54b80eb5fcf6c9d203b37/)',
		];
	} else {
		texts = Object.entries(data).map(([key, val]) => `${key}:${val}`);
	}

	return (
		<Tooltip
			placement="top"
			overlay={
				<div className={s.payloadOverlay}>
					{texts.map(x => (
						<div key={x} className={s.item}>
							<Label className={s.label}> </Label> <p className={s.text}>{x}</p>
						</div>
					))}
				</div>
			}
		>
			<div className={cn(s.test, s.hl)}>
				{texts.map(x => (
					<span key={x}>{x}</span>
				))}
			</div>
		</Tooltip>
	);
};
function TaskSettingsViewer({
	className,
	children,
	host,
	taskType,
	taskSettings,
	jobId,
	name,
	isLatestTask,
	alertSettings,
	triggerType,
}) {
	const NODE_ID_LABEL_MAP_ = Object.assign(
		NODE_ID_LABEL_MAP,
		NODE_ID_LABEL_MAP2
	);
	const TRIGGER_TYPE = { schedule: '周期性', manual: '自定义单次' };
	const { data: alertData } = useQuery(ALERT_GROUP_QUERY);
	const [groupData, setGroupData] = React.useState([]);
	const [visible, setVisible] = React.useState(false);
	const { collect = {}, alert = {} } = taskSettings || {};
	const notigicationArr = [];
	const groupArr = [];
	alertSettings &&
		INFORM_OPTIONS.forEach(e => {
			alertSettings.notification[e.value] && notigicationArr.push(e.label);
		});
	React.useEffect(() => {
		if (alertSettings && alertData) {
			alertData.AlertGroupMany.forEach(e => {
				if (alertSettings.alertGroupIds.includes(e._id)) {
					groupArr.push(e.name);
				}
			});
		}
		setGroupData(groupArr);
	}, [alertData]);
	return (
		<>
			<Button
				link
				primary
				className={cn(className, s.btn)}
				onClick={() => setVisible(true)}
			>
				{children}
			</Button>
			<Dialog
				title={
					<div className={s.dialogtitle}>
						<span>{children}</span>
						<Helper
							overlayClassName={s.helpTooltip}
							overlay={
								<>
									<p>以下配置为该资产当次任务检测时设置的参数。</p>
									<p>
										如需查看最新周期性参数配置，请前往“资产列表-管理-周期配置”
									</p>
								</>
							}
							placement="right"
						/>
					</div>
				}
				visible={visible}
				prefixCls={s.dialog}
				className={s.modal}
				onClose={() => setVisible(false)}
			>
				<table>
					<tbody>
						<tr>
							<td className={cn(s.field, s.label)}>任务名称:</td>
							<td className={s.value}>{name}</td>
						</tr>
						<tr>
							<td className={cn(s.field, s.label)}>资产地址:</td>
							<td className={s.value}>
								<div className={s.host}>{host}</div>
							</td>
						</tr>
						<tr>
							<td className={cn(s.field, s.label)}>监测方式:</td>
							<td className={s.value}>
								<span>{triggerType ? TRIGGER_TYPE[triggerType] : ''}</span>
							</td>
						</tr>
						<tr>
							<td className={cn(s.field, s.label)}>监测节点:</td>
							<td className={s.value}>
								{collect?.area?.length > 0 && (
									<span className={s.hl}>
										<>
											<span>
												IPv4：
												{`${NODE_ID_LABEL_MAP_[collect.area[0]]}
											${collect?.area?.length > 1 && `等${collect.area.length}个监测节点`}`}
											</span>

											{collect?.area?.length > 1 && (
												<Tooltip
													placement="top"
													overlay={
														<span className={s.tipSpan}>
															{collect.area.map((e, i) => {
																return `${NODE_ID_LABEL_MAP_[e]}${
																	i >= collect.area.length - 1 ? '' : '，'
																}`;
															})}
														</span>
													}
													overlayClassName={s.helpTooltip}
												>
													<EyeOutlined
														style={{ fontSize: '16px', color: '#08c' }}
													/>
												</Tooltip>
											)}
										</>
									</span>
								)}
								{collect?.area_ipv6?.length > 0 && (
									<span className={s.hl}>
										<>
											<span>
												IPv6：
												{`${NODE_ID_LABEL_MAP_[collect.area_ipv6[0]]}
											${collect?.area_ipv6?.length > 1 && `等${collect.area_ipv6.length}个监测节点`}`}
											</span>
											{collect?.area_ipv6?.length > 1 && (
												<Tooltip
													placement="top"
													overlay={
														<span className={s.tipSpan}>
															{collect.area_ipv6.map((e, i) => {
																return `${NODE_ID_LABEL_MAP_[e]}${
																	i >= collect.area_ipv6.length - 1 ? '' : '，'
																}`;
															})}
														</span>
													}
													overlayClassName={s.helpTooltip}
												>
													<EyeOutlined
														style={{ fontSize: '16px', color: '#08c' }}
													/>
												</Tooltip>
											)}
										</>
									</span>
								)}
							</td>
						</tr>
						<tr>
							<td className={cn(s.field, s.label)}>监测频率:</td>
							<td className={s.value}>
								<span className={s.hl}>
									<CollectFrequency
										viewmode
										numbers={PING_FREQUENCY_NUMBERS}
										unitMap={WEAKNESS_FREQUENCY_UNIT_MAP}
										value={taskSettings?.interval}
									/>
								</span>
							</td>
						</tr>
						{taskType === 'http' && (
							<>
								<tr>
									<td className={cn(s.field, s.label)}>HTTP请求方法:</td>
									<td className={s.value}>
										<span>{collect?.method?.toUpperCase()}</span>
									</td>
								</tr>
								<tr className={s.collectSetting}>
									<td className={cn(s.field, s.label)}>HTTP请求信息:</td>
									<td className={cn(s.test, s.value)}>
										{httpSubmitInnerBuilder(collect?.header)}
									</td>
								</tr>
								{collect.payload && (
									<tr className={s.collectSettingItem}>
										<td className={s.field}>提交内容</td>
										<td className={cn(s.hl, s.payload)}>{collect.payload}</td>
									</tr>
								)}
								<tr>
									<td className={s.field}>重定向次数:</td>
									<td>
										允许页面最多跳转
										<span>{collect?.redirect}</span>次
									</td>
								</tr>
							</>
						)}
						<tr>
							<td className={cn(s.field, s.label)}>告警策略:</td>
							<td className={s.value}>
								<div className={s.collectSettingItem}>
									<span className={s.field}>异常条件</span>
									<div>
										<div>
											响应时间大于等于<span>{alert?.respTime}</span>或
										</div>
										{taskType === 'ping' && alert?.lossRate && (
											<div>
												丢包率大于等于<span>{alert?.lossRate}%</span>时告警
											</div>
										)}
									</div>
								</div>
								{taskType === 'http' && (
									<>
										<div className={s.collectSettingItem}>
											<span className={s.field}>状态码告警</span>
											<span>
												<span className={s.status}>
													{alert.statusCodeRange?.map((code, idx) => (
														<span key={idx} className={s.code}>
															{code.length > 1 ? code.join('~') : code}
														</span>
													))}
												</span>
											</span>
										</div>
										{alert?.include && alert?.include?.length > 0 && (
											<div className={s.collectSettingItem}>
												<span className={s.field}>包含关键字告警</span>
												<span>
													<span className={s.keywords}>
														{alert?.include.map(w => (
															<span key={w} className={s.code}>
																{w}
															</span>
														))}
													</span>
												</span>
											</div>
										)}
									</>
								)}
								<div className={s.collectSettingItem}>
									<span className={s.field}>告警节点数</span>
									<span>
										异常节点数大于等于<span>{alert?.nodeCount}</span>个时告警
									</span>
								</div>
								<div className={s.collectSettingItem}>
									<span className={s.field}>告警次数</span>
									<span>
										每次告警或故障最多告警<span>{alert?.alertCount}</span>次
									</span>
								</div>
							</td>
						</tr>
						{alertSettings && (
							<>
								<tr>
									<td className={s.field}>通知对象：</td>
									<td className={s.value}>
										{groupData[0]
											? groupData.map(e => {
													return (
														<span className={s.hl2} key={e}>
															{e}
														</span>
													);
											  })
											: '--'}
									</td>
								</tr>
								<tr>
									<td className={s.field}>通知类型：</td>
									<td className={s.value}>
										{notigicationArr[0]
											? notigicationArr.map((e, i) => {
													return (
														<span key={e}>
															{e}
															{i === notigicationArr.length - 1 ? '' : '、'}
														</span>
													);
											  })
											: '--'}
									</td>
								</tr>
							</>
						)}
					</tbody>
				</table>
				<div className={s.actions}>
					{jobId && isLatestTask && (
						<Link className={s.link} to={`/job/${jobId}/aviliable/${taskType}`}>
							<Button className={s.actionBtn}>前往修改</Button>
						</Link>
					)}
					<Button
						primary
						className={s.actionBtn}
						onClick={() => setVisible(false)}
					>
						取消
					</Button>
				</div>
			</Dialog>
		</>
	);
}

TaskSettingsViewer.propTypes = {
	className: PropTypes.string,
	children: PropTypes.node,
	host: PropTypes.string.isRequired,
	taskType: PropTypes.string.isRequired,
	triggerType: PropTypes.string.isRequired,
	jobId: PropTypes.string,
	isLatestTask: PropTypes.bool,
	taskSettings: PropTypes.shape({
		collect: PropTypes.object.isRequired,
		interval: PropTypes.number.isRequired,
		enable: PropTypes.bool,
		alert: PropTypes.object,
	}),
	name: PropTypes.string,
	alertSettings: PropTypes.any,
};
TaskSettingsViewer.defaultProps = {
	className: '',
	isLatestTask: true,
};

export default TaskSettingsViewer;
